<?php

namespace Framework\Foundation;

/**
 * Class Config
 */
class Config
{
    //创建静态私有的变量保存该类对象
    private static $instance;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private $configData = [];

    public function get($key, $default = null)
    {
        if (is_null($key)) {
            return $this->configData;
        }

        if (false === strpos($key, '.')) {
            return $this->configData[$key] ?? $default;
        }

        $keys = explode('.', $key);
        $configFile = $keys[0];
        if (!isset($this->configData[$configFile])) {
            $this->configData[$configFile] = $this->loadConfig($configFile);
        }

        $subConfig = $this->configData[$configFile];
        for ($i = 1; $i < count($keys); $i++) {
            if ('' == $keys[$i]) {
                return $subConfig;
            }
            if (!isset($subConfig[$keys[$i]])) {
                return $default;
            }
            $subConfig = $subConfig[$keys[$i]];
        }
        return $subConfig;
    }

    public function set(string $key, $value)
    {
        if (false === strpos($key, '.')) {
            return false;
        }

        $keys = explode('.', $key);

        $count = count($keys);

        $configSet = &$this->configData;
        for ($i = 0; $i < $count; $i++) {
            $currentKey = array_shift($keys);
            if (!isset($configSet[$currentKey])) {
                $configSet[$currentKey] = $this->processUnIndexKey($keys, $value);
                break;
            } else {
                $configSet = &$configSet[$currentKey];
            }
        }

        return true;
    }

    protected function processUnIndexKey($keys, $value)
    {
        if (empty($keys)) {
            return $value;
        }

        $reversed = array_reverse($keys);
        $data = [];

        $i = 0;
        foreach ($reversed as $k) {
            if ($i == 0) {
                $data[$k] = $value;
                $i++;
                continue;
            }
            $tempData = $data;
            $data = array($k => $tempData);
            $i++;
        }

        return $data;
    }

    /**
     * @param $configFile
     * @return array
     */
    protected function loadConfig($configFile)
    {
        $file = ROOT . '/app/config/' . $configFile . '.php';
        if (file_exists($file)) {
            return include $file;
        }

        return [];
    }

//    public static function __callStatic($name, $arguments)
//    {
//
//    }
}
